#include <stdio.h> 
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "common_func.h"
#include "spi.h"
#include "spi_flash_en25f80.h"
#include "gpio.h"

#define RAM_SIZE  512

int  simu_flag;

int main(int argc, char** argv)
{	
	uint16_t flash_id;
    uint32_t i;
	uint8_t ram[RAM_SIZE];
	uint8_t read_ram[RAM_SIZE];

	simu_flag = RegRead(0xbf20f500);

	printf("SPI TEST BEGIN\n");

	// Prepare Ram Data 0-255 0-255 ...
	for(i = 0; i<RAM_SIZE; i=i+1){
		ram[i] = i;
	}

	// Init SPI
	gpio_iof_config(GPIOA, IOF_SPI_SCK_MASK | IOF_SPI_MOSI_MASK | IOF_SPI_MISO_MASK);
	gpio_enable_output(GPIOA, IOF_SPI_SS0_MASK);
	spi_cs_up();
	spi_setup_clk(SPI0, 20);
	spi_start_transaction(SPI0, SPI_CMD_SWRST, SPI_CSN0);

	// Read FLASH ID
	spi_flash_read_id();

	// 仿真环境里仅模拟了读ID功能
	if(simu_flag){
		printf("SPI TEST PASS!!\n");
		return 0;
	}

	// Erase and Write FLASH
	spi_flash_erase_write((unsigned int)(&ram[0]), 0x0, RAM_SIZE);

	// Read FLASH Data
	spi_flash_read_area(0x0,read_ram,RAM_SIZE);

	// Check FLASH Read Date
	for(i = 0; i<RAM_SIZE; i=i+1){
		if(read_ram[i] != ram[i]){
			printf("Error : read_ram[%d] = %d, ram[%d] = %d\n",i,read_ram[i],i,ram[i]);
			break;
		}
	}
	printf("SPI TEST PASS!!\n");
	printf("read_ram[0]=%d\n",read_ram[0]);
	printf("read_ram[1]=%d\n",read_ram[1]);
	printf("read_ram[%d]=%d\n",RAM_SIZE-2,read_ram[RAM_SIZE-2]);
	printf("read_ram[%d]=%d\n",RAM_SIZE-1,read_ram[RAM_SIZE-1]);

	return 0;
}